package com.opc.utils;

import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.core.JIArray;
import org.jinterop.dcom.core.JIVariant;
import org.openscada.opc.dcom.list.ClassDetails;
import org.openscada.opc.lib.common.AlreadyConnectedException;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.common.NotConnectedException;
import org.openscada.opc.lib.da.*;
import org.openscada.opc.lib.da.browser.FlatBrowser;
import org.openscada.opc.lib.list.Categories;
import org.openscada.opc.lib.list.Category;
import org.openscada.opc.lib.list.ServerList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;


/**
 * @author SEG
 */
public class OpcClient extends Observable {
    private Server mServer = null;
    private static final Logger log = LoggerFactory.getLogger(OpcClient.class);
    public Integer corePoolSize = 5;

    /**
     * 连接opc server
     */
    public synchronized boolean connectServer(String host, String clsId, String user, String password, String domain) {
        boolean mState = false;
        try {
            // 连接server
            final ConnectionInformation connectionInfo = new ConnectionInformation();
            connectionInfo.setHost(host);
            // TODO 设置ProgId，无法连接server；设置Clsid，连接server成功
            connectionInfo.setClsid(clsId);
            connectionInfo.setUser(user);
            connectionInfo.setPassword(password);

            ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
            mServer = new Server(connectionInfo, executor);
            mServer.connect();

            mServer.addStateListener(state -> log.info("connectionStateChanged state:{}", state));

            mState = true;
        } catch (IllegalArgumentException | UnknownHostException | JIException | AlreadyConnectedException e) {
            e.printStackTrace();
        } finally {
            if (!mState) {
                mServer = null;
            }
        }

        return mState;
    }

    /**
     * 断开连接opc server
     */
    public synchronized void disconnectServer() {
        if (mServer == null) {
            return;
        }
        mServer.disconnect();
        mServer = null;
    }

    /**
     * 显示server上的OPC服务器应用列表
     */
    public void showAllOPCServer(String host, String user, String password, String domain) {
        try {
            ServerList serverList = new ServerList(host, user, password, domain);
            // 支持DA 1.0，DA 2.0规范
            Collection<ClassDetails> detailsList = serverList.listServersWithDetails(
                    new Category[]{Categories.OPCDAServer10, Categories.OPCDAServer20}, new Category[]{});
            for (final ClassDetails details : detailsList) {
                log.info("ClsId: {} , ProgId: {} , Description: {}", details.getClsId(), details.getProgId(), details.getDescription());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查opc server中是否包含指定的监测点列表
     */
    public boolean checkItemList(List<String> list) {
        // 获取opc server上的所有检测点
        FlatBrowser flatBrowser = mServer.getFlatBrowser();
        if (flatBrowser == null) {
            return false;
        }
        try {
            Collection<String> collection = flatBrowser.browse();
            return collection.containsAll(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public Collection<String> ALLItemList() {
        // 获取opc server上的所有检测点
        FlatBrowser flatBrowser = mServer.getFlatBrowser();
        if (flatBrowser == null) {
            return null;
        }
        try {
            Collection<String> collection = flatBrowser.browse();
            return collection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 异步读取数据 Async20Access实现了IOPCDataCallback接口，基于事件回调的实现
     */
    public void asyncReadObject(final String itemId, int period) {
        // 第三个参数用于设置初始化时是否执行访问
        AccessBase accessBase;
        try {
            accessBase = new Async20Access(mServer, period, false);
            accessBase.addItem(itemId, (item, itemState) -> {
                log.info("asyncReadObject item: {}", itemState);
                try {
                    Object value = itemState.getValue().getObject();
                    setData(itemId, value);
                } catch (JIException e) {
                    e.printStackTrace();
                }
            });
            // 开始读取
            accessBase.bind();
        } catch (IllegalArgumentException | UnknownHostException | NotConnectedException | JIException |
                 DuplicateGroupException | AddFailedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 同步读取数据
     */
    public void syncReadObject(final String itemId, int period) {
        AccessBase accessBase;
        try {
            // SyncAccess会开启一个线程，按照period时间间隔，定时去获取监控点数据
            accessBase = new SyncAccess(mServer, period);
            accessBase.addStateListener(new AccessStateListener() {
                @Override
                public void stateChanged(boolean state) {
                    log.info("state Changed state: {}", state);
                }

                @Override
                public void errorOccured(Throwable arg) {
                    log.error("error occur arg :{}", arg);
                }
            });
            accessBase.addItem(itemId, (item, itemState) -> {
                log.info("syncReadObject item======:{}", itemState);
                if (itemState == null) {
                    log.info("itemState is null");
                    return;
                }
                String value = getValue(itemState);
                setData(itemId, value);
            });
            // 开始读取
            accessBase.bind();
        } catch (IllegalArgumentException | UnknownHostException | NotConnectedException | JIException |
                 DuplicateGroupException | AddFailedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册
     */
    public void subscribe(Observer observer) {
        this.addObserver(observer);
    }

    /**
     * 数据变化，通知观察者
     */
    private void setData(String itemId, Object value) {
        setChanged();
        notifyObservers(new Result(itemId, value));
    }


    /**
     * 如果是 bool、string、short、int等直接返回字符串；
     * 如果是 long 类型的数组,返回数字内容间加点，对应 long，数组，大小为6
     * 如果是 float 类型的数组,返回数字内容间加逗号，对应 float，数组，大小为20
     */
    private static String getValue(ItemState state) {
        JIVariant variant = state.getValue();
        try {
            int type = variant.getType();
            //Boolean
            if (type == JIVariant.VT_BOOL) {
                boolean value = variant.getObjectAsBoolean();
                return String.valueOf(value);
            }
            //String
            else if (type == JIVariant.VT_BSTR) {
                return variant.getObjectAsString().getString();
            }
            //Word DWord
            else if (type == JIVariant.VT_UI2 || type == JIVariant.VT_UI4) {
                Number value = variant.getObjectAsUnsigned().getValue();
                return String.valueOf(value);
            }
            //Sort
            else if (type == JIVariant.VT_I2) {
                short value = variant.getObjectAsShort();
                return String.valueOf(value);
            }
            //Float
            else if (type == JIVariant.VT_R4) {
                float value = variant.getObjectAsFloat();
                return String.valueOf(value);
            }
            //long 类型的数组
            else if (type == 8195) {
                JIArray jarr = variant.getObjectAsArray();
                Integer[] arr = (Integer[]) jarr.getArrayInstance();
                StringBuilder value = new StringBuilder();
                for (Integer i : arr) {
                    value.append(i).append(".");
                }
                String res = value.substring(0, value.length() - 1);
                // "25.36087601.1.1.18.36"-->"25.36087601.01.0001.18.36"
                String[] array = res.split("[.]");
                return array[0] + "." + array[1] + "." + new DecimalFormat("00").format(Long.valueOf(array[2]))
                        + "." + new DecimalFormat("0000").format(Long.valueOf(array[3])) + "." + array[4] + "."
                        + array[5];
            }
            //float 类型的数组
            else if (type == 8196) {
                JIArray jarr = variant.getObjectAsArray();
                Float[] arr = (Float[]) jarr.getArrayInstance();
                StringBuilder value = new StringBuilder();
                for (Float f : arr) {
                    value.append(f).append(",");
                }
                return value.substring(0, value.length() - 1);
            } else if (type == JIVariant.VT_EMPTY) {
                return String.valueOf(-1);
            }
            //其他类型
            else {
                Object value = variant.getObject();
                return String.valueOf(value);
            }
        } catch (JIException e) {
            e.printStackTrace();
        }
        return null;
    }


}
